package com.dobest.securitydemo3.service.impl;

import com.dobest.securitydemo3.dao.RoleRepository;
import com.dobest.securitydemo3.dao.UserRepository;
import com.dobest.securitydemo3.dao.UserRoleRepository;
import com.dobest.securitydemo3.domain.Role;
import com.dobest.securitydemo3.domain.User;
import com.dobest.securitydemo3.domain.UserRole;
import com.dobest.securitydemo3.domain.vo.UserVo;
import com.dobest.securitydemo3.service.IUserService;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Copyright © 2018胡建松. All rights reserved.
 *
 * @Package: com.dobest.securitydemo3.service.impl
 * @author: hujiansong
 * @date: 2018/7/20 15:55
 * @version: V1.0
 */
@Service
public class UserService implements IUserService {
    @Autowired
    UserRepository userRepository;

    @Autowired
    UserRoleRepository userRoleRepository;

    @Autowired
    RoleRepository roleRepository;

    @Autowired
    ModelMapper modelMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userRepository.findUserByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("不存在该用户~");
        }

        List<UserRole> userRoles = userRoleRepository.findAllByUserId(user.getId());

        if (userRoles == null) {
            throw new UsernameNotFoundException("非法用户~");
        }
        Set<Integer> roleIds = new HashSet<>();
        userRoles.forEach(userRole -> roleIds.add(userRole.getRoleId()));
        List<Role> roles = roleRepository.findRolesByIdIn(roleIds);
        UserVo userVo = modelMapper.map(user, UserVo.class);
        userVo.setRoles(roles);

        return userVo;
    }
}
